package com.kjsdfgk.hjmdsf.myphoto.mvp.presenter;

import android.app.Application;

import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.jess.arms.utils.RxLifecycleUtils;
import com.kjsdfgk.hjmdsf.app.entity.WebPhoto;
import com.kjsdfgk.hjmdsf.myphoto.mvp.contract.MyPhotoContract;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/10/2020 00:28
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class MyPhotoPresenter extends BasePresenter<MyPhotoContract.Model, MyPhotoContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public MyPhotoPresenter (MyPhotoContract.Model model, MyPhotoContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
    int page = 1;
    public void getImgs(String href) {
        page = 1;
        mModel.getImgs(href ,page++)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(new Date().toString()))
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        mRootView.showMessage(e.toString());

                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        mRootView.hideLoading();
                        mRootView.showWebPhoto(parseJPG(result , true));
                    }
                });
    }
    public void loadImagesMore(String href) {
        mModel.getImgs(href ,page++)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> mRootView.showLoading(new Date().toString()))
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {

                        mRootView.hideLoading();
                        mRootView.updateTextTipEnd( );
                        mRootView.showMessage("无更多图片");
                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        mRootView.hideLoading();
                        mRootView.showWebPhotoMore(parseJPG(result, true));
                        mRootView.updateTextTip();
                    }
                });
    }
    private List<WebPhoto> parseJPG(String result, boolean b) {
        try {
//            Jsoup.parse(result).select("img").get(28).attributes().asList().get(0).getValue();

            List<WebPhoto> photoList = new ArrayList<>();
            for (Element element : Jsoup.parse(result).select("img")){
                System.out.println(element);
                if (element.attributes().html().contains("content_img")){
                    WebPhoto webPhoto = new WebPhoto();
                    for (Attribute a:element.attributes().asList()){
                        if ("src".equals(a.getKey())){
                            webPhoto.url = a.getValue();
                            photoList.add(webPhoto);
                        }
                     }
                    }
                }
            return photoList;
        }catch (Exception e){
            mRootView.showMessage(e.toString());
        }
        return null;
    }


    public void autoDownlaod(String href ) {
        mModel.getImgs(href ,page++)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .retryWhen(new RetryWithDelay(3, 2))
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onError(@NonNull Throwable e) {
                        mRootView.hideLoading();
                        mRootView.downloadList();
                    }

                    @Override
                    public void onNext(@NonNull String result) {
                        mRootView.hideLoading();
                        mRootView.showWebPhotoMoreX(parseJPG(result, true));
                        mRootView.updateTextTip();

                    }
                });
    }
}
